﻿using CommunityToolkit.Mvvm.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MachineVision.Core.Util.Navigation
{
    internal static class CommonTool
    {
        internal static Type GetTypeBaseonName(string name)
        {
            var types = Assembly.GetEntryAssembly()?.GetTypes();
            Type? type = null;
            foreach (var temp in types)
            {
                if (temp.Name.Equals(name))
                {
                    type = temp;
                }
            }
            return type;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="regionName"></param>
        /// <param name="targetUserControlName"></param>
        /// <returns></returns>
        internal static void Navigate(string regionName, string targetViewName)
        {
            if (string.IsNullOrEmpty(regionName))
            {
                throw new Exception($"导航动作未设置目标Region");
            }
            if (string.IsNullOrEmpty(targetViewName))
            {
                throw new Exception($"导航动作未设置目标View");
            }
            RegionManager regionCollection = Ioc.Default.GetService<RegionManager>() ?? throw new Exception($"DI容器中找不到区域容器RegionManager");
            if (regionCollection.RegionMaps.ContainsKey(regionName))
            {
                try
                {
                    Type type = GetTypeBaseonName(targetViewName) ?? throw new Exception($"在程序集{Assembly.GetEntryAssembly()}中找不到名为{targetViewName}的类型");
                    var targetView = Ioc.Default.GetService(type) ?? throw new Exception($"DI容器中找不到类型{type.FullName}");
                    regionCollection.RegionMaps[regionName].Content = targetView;
                    return;
                }
                catch (Exception)
                {
                    return;
                }
                
            }
            else
            {
                throw new Exception($"区域容器中找不到名为{regionName}的区域");
            }
        }
    }
}